package com.fuqi.android.zhongcai.business.shuig.view.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.error.VolleyError;
import com.fuqi.android.zhongcai.R;
import com.fuqi.android.zhongcai.base.request.api.PushImgApi;
import com.fuqi.android.zhongcai.base.request.result.PushResult;
import com.fuqi.android.zhongcai.base.view.activity.BaseActivity;
import com.fuqi.android.zhongcai.base.view.widget.CustomProgress;
import com.fuqi.android.zhongcai.business.shuig.lintener.ConfirmListener;
import com.fuqi.android.zhongcai.business.shuig.request.api.CheckApi;
import com.fuqi.android.zhongcai.business.shuig.request.api.CreateCheckApi;
import com.fuqi.android.zhongcai.business.shuig.request.result.CheckInfoResult;
import com.fuqi.android.zhongcai.business.shuig.request.result.CreateCheckResult;
import com.fuqi.android.zhongcai.business.shuig.request.result.bean.Check;
import com.fuqi.android.zhongcai.business.shuig.view.adapter.ChouChaAdapter;
import com.fuqi.android.zhongcai.business.shuig.view.widget.CJRow.ARResponse;
import com.fuqi.android.zhongcai.utils.ActivityUtils;
import com.fuqi.android.zhongcai.utils.FileUtil;
import com.fuqi.android.zhongcai.utils.ImageUtils;
import com.fuqi.android.zhongcai.utils.RegexUtil;
import com.fuqi.framework.gson.GsonHelper;
import com.fuqi.framework.network.code.HandleCode;
import com.fuqi.framework.network.http.RequestManager;
import com.fuqi.framework.utils.StringUtil;
import com.google.gson.JsonArray;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerActivity;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerPreviewActivity;
import cn.bingoogolapple.photopicker.widget.BGASortableNinePhotoLayout;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class ShuiGChouChaActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks,BGASortableNinePhotoLayout.Delegate{
    @Bind(R.id.sv_body)
    ScrollView mSvBody;
    @Bind(R.id.lv_questionList)
    ListView mLvQuestion;
    @Bind(R.id.et_fdje)
    EditText mEtFdje;
    @Bind(R.id.et_fdyy)
    EditText mEtFdyy;
    @Bind(R.id.activity_discover_invest_publish_picture_iv)
    ImageView mIvPub;
    @Bind(R.id.rl_item2)
    View mLytItem2;

    ChouChaAdapter mQuestionAdapter;
    List<Check> questionData = new ArrayList<Check>();

    String sQuestionList;
    ARResponse response;

    private BGASortableNinePhotoLayout ninePhotoLayout;
    //    选择头像请求码
    private static final int REQUEST_CODE_PERMISSION_PHOTO_PICKER = 1;
    private static final int REQUEST_CODE_CHOOSE_PHOTO = 1;
    private static final int REQUEST_CODE_PHOTO_PREVIEW = 2;
//    private ArrayList<String> selectedPhotos = new ArrayList<>();
    private static final int MAX_PHOTO_COUNT = 9;

    private ArrayList<String> netPhotos = new ArrayList<>();
    String sPicString;

    @OnClick({R.id.okadvice,R.id.activity_discover_invest_publish_picture_iv})
    public void onClickListener(View view) {

        switch (view.getId()) {
            case R.id.activity_discover_invest_publish_picture_iv:
                choicePhotoWrapper();
                break;
            case R.id.okadvice:
                JsonArray jsonArray = mQuestionAdapter.getItem();
                sQuestionList = jsonArray.toString();
                if(jsonArray.size() < questionData.size()) {
                    ActivityUtils.toast("请完成审核再提交");
                    break;
                }

                if(mLytItem2.getVisibility() == View.VISIBLE){
                    // TODO 有罚单
                    netPhotos = ninePhotoLayout.getData();
                    if(!RegexUtil.checkNotNull(mEtFdje.getText().toString())){
                        ActivityUtils.toast("请输入金额。");
                        return;
                    }else if(!RegexUtil.checkFloat(mEtFdje.getText().toString())){
                        ActivityUtils.toast("请输入正确金额。");
                        return;
                    }else if(!RegexUtil.checkNotNull(mEtFdyy.getText().toString())){
                        ActivityUtils.toast("请输入原因。");
                        return;
                    }else if(netPhotos.size() == 0){
                        ActivityUtils.toast("请上传图片。");
                        return;
                    }

                    doUpload();
                }else{
                    // TODO 无罚单
                    doPublish();
                }



                break;
        }
    }

    Response.Listener<PushResult> respWorkersListener = new Response.Listener<PushResult>() {

        @Override
        public void onResponse(PushResult response) {
            CustomProgress.close();
            FileUtil.clearDir(FileUtil.getTempFile());
            if (HandleCode.requestSuccess()) {
                netPhotos.addAll(StringUtil.getList(response.getPath(),","));
//                if(netPhotos.size() == selectedPhotos.size()) {
                    doPublish();
//                }
                Log.i("juner", "juner respWorkersListener response : " + response.getPath());
            } else {
            }
        }
    };

    Response.Listener<CreateCheckResult> respfListener = new Response.Listener<CreateCheckResult>() {

        @Override
        public void onResponse(CreateCheckResult response) {
            if (HandleCode.requestSuccess()) {
                ActivityUtils.toast("抽查完成。");
                finish();
                Log.i("juner", "juner OrderDetailResult response : " + GsonHelper.writeValue(response));
            } else {
            }
        }
    };

    Response.Listener<CheckInfoResult> respListener = new Response.Listener<CheckInfoResult>() {

        @Override
        public void onResponse(CheckInfoResult response) {
            CustomProgress.close();
            if (HandleCode.requestSuccess()) {
                questionData = response.getCheckList();
                mQuestionAdapter.setDate(questionData);
                Log.i("juner", "juner OrderDetailResult response : " + GsonHelper.writeValue(response));
            } else {
            }
        }
    };

    Response.ErrorListener errorListener = new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            CustomProgress.close();
            FileUtil.clearDir(FileUtil.getTempFile());
            Log.i("juner", "juner  error.getMessage(): " + error.getMessage());
        }
    };

    private void doPublish(){
        sPicString = StringUtil.getListString(netPhotos);

        RequestManager.getInstance().call(new CreateCheckApi(
                new CreateCheckApi.CreateCheckParams(response.getValue("ORDER_ID"),sQuestionList,
                        mEtFdje.getText().toString(),mEtFdyy.getText().toString(),
                        sPicString),
                respfListener, errorListener));

    }

    private void doUpload(){
        ActivityUtils.toast("图片处理中...");
        ninePhotoLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                List<File> files = ImageUtils.makePaths2ImgFileList(netPhotos);
                netPhotos.clear();
                CustomProgress.show(ShuiGChouChaActivity.this, "正在上传...", true, null);
                PushImgApi p = new PushImgApi(respWorkersListener, errorListener, "files", files, null);
                RequestManager.getInstance().call(p);
            }
        },100);
    }


    @Override
    public void initView() {
        titleBar.setTitle("监理抽查");
        ninePhotoLayout = (BGASortableNinePhotoLayout) findViewById(R.id.activity_discover_invest_publish_nine_photo);
        ninePhotoLayout.init(ShuiGChouChaActivity.this);
        ninePhotoLayout.setDelegate(ShuiGChouChaActivity.this);
        mSvBody.post(new Runnable() {
            @Override
            public void run() {
                mSvBody.fullScroll(ScrollView.FOCUS_UP);
            }
        });
    }
    @Override
    public void initListener() {
        mQuestionAdapter.setListener(new ConfirmListener() {
            @Override
            public void onListener(boolean ischeck) {
                mLytItem2.setVisibility(ischeck?View.VISIBLE:View.GONE);
                mSvBody.post(new Runnable() {
                    @Override
                    public void run() {
                        mSvBody.fullScroll(ScrollView.FOCUS_DOWN);
                    }
                });
            }
        });
    }

    @Override
    public void initData() {
        response = new ARResponse(getIntent().getStringExtra("response"));

        mQuestionAdapter = new ChouChaAdapter(this, questionData);

        RequestManager.getInstance().call(new CheckApi(
                new CheckApi.CheckParams(), respListener, errorListener));

        mLvQuestion.setAdapter(mQuestionAdapter);
    }

    @Override
    public boolean hasTitleBar() {
        return true;
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_choucha;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_CHOOSE_PHOTO) {
            ninePhotoLayout.setData(BGAPhotoPickerActivity.getSelectedImages(data));
            mIvPub.setVisibility(View.GONE);
        } else if (requestCode == REQUEST_CODE_PHOTO_PREVIEW) {
            ninePhotoLayout.setData(BGAPhotoPickerPreviewActivity.getSelectedImages(data));
        }
    }

    @AfterPermissionGranted(REQUEST_CODE_PERMISSION_PHOTO_PICKER)
    private void choicePhotoWrapper() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(this, perms)) {
            // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话就没有拍照功能
            File takePhotoDir = new File(Environment.getExternalStorageDirectory(), "ZhongCDownload");

            startActivityForResult(BGAPhotoPickerActivity.newIntent(this, takePhotoDir, 9, ninePhotoLayout.getData()), REQUEST_CODE_CHOOSE_PHOTO);
        } else {
            EasyPermissions.requestPermissions(this, "图片选择需要以下权限:\n\n1.访问设备上的照片", REQUEST_CODE_PERMISSION_PHOTO_PICKER, perms);
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (requestCode == REQUEST_CODE_PERMISSION_PHOTO_PICKER) {
            Toast.makeText(this, "您拒绝了「图片选择」所需要的相关权限!", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onClickAddNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, ArrayList<String> models) {
        choicePhotoWrapper();
    }

    @Override
    public void onClickDeleteNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        ninePhotoLayout.removeItem(position);
    }

    @Override
    public void onClickNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        startActivityForResult(BGAPhotoPickerPreviewActivity.newIntent(this, MAX_PHOTO_COUNT, models, models, position, false), REQUEST_CODE_PHOTO_PREVIEW);
    }

}
